﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Xml;
using ZQNB.Common.Models;

namespace ZQNB.Common
{
    public class MyConfigHelper
    {
        public static void ChangeAppSettingForWeb(string theKey, string theValue)
        {
            string configPath = HttpContext.Current.Server.MapPath("Web.config");
            ChangeAppSetting(configPath, theKey, theValue);
        }

        public static void ChangeAppSetting(string configPath, string theKey, string theValue)
        {
            try
            {
                XmlDocument xDoc = new XmlDocument();
                xDoc.Load(configPath);
                XmlNodeList nodeList = xDoc.GetElementsByTagName("appSettings");
                XmlNodeList nodeAppSettings = nodeList[0].ChildNodes;
                foreach (XmlNode item in nodeAppSettings)
                {
                    if (item.Name.ToLower() == "add")
                    {
                        var key = item.Attributes["key"];
                        if (key != null && key.Value == theKey)
                        {
                            var value = item.Attributes["value"];
                            value.Value = theValue;
                            xDoc.Save(configPath);
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new NbException(string.Format("修改配置节{0}出现异常: ", theKey) + ex.Message);
            }
        }
    }
}
